package com.zhiwang.planet.mvvm.model

import android.annotation.SuppressLint
import android.util.Log
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import okhttp3.logging.HttpLoggingInterceptor

open class OkHttpLogger : HttpLoggingInterceptor.Logger {
    private val TAG = "OkHttpLogger"
    @SuppressLint("LogNotTimber")
    override fun log(message: String) {
        LogUtil.logOkHttp(message)
    }

    open class LogUtil {

        companion object LOGSOUL {
            private const val TAG = "LogUtil"
            private val gson = GsonBuilder().setPrettyPrinting().create()
            private val httpStringBuilder = StringBuffer(256)
            private const val HTTP_START_REQUEST_TAG = "════════════════════════════════请求开始═══════════════════════"
            private const val HTTP_END_REQUEST_TAG = "════════════════════════════════请求结束═══════════════════════"
            private const val HTTP__START_RESPONSE_TAG = "════════════════════════════════响应开始═══════════════════════"
            private const val HTTP__END_RESPONSE_TAG = "════════════════════════════════响应结束═══════════════════════"

            fun logOkHttp(msg: String) {
                addFormatTagWithLog(msg)
                if (msg.startsWith("<-- END HTTP"))
                    printLog()
            }

            @SuppressLint("LogNotTimber")
            private fun printLog() {
                Log.i("", httpStringBuilder.toString())
                httpStringBuilder.delete(0, httpStringBuilder.count())
            }

            private fun addFormatTagWithLog(msg: String) {
                when {
                    msg.startsWith("--> POST") -> {
                        httpStringBuilder.append("\n" + HTTP_START_REQUEST_TAG + "\n")
                        httpStringBuilder.append("\n" + HTTP_START_REQUEST_TAG + "\n")
                        addHttpLogInfo(msg)
                    }
                    msg.startsWith("--> END POST") -> {
                        addHttpLogInfo(msg)
                        httpStringBuilder.append(HTTP_END_REQUEST_TAG + "\n")
                    }
                    msg.startsWith("<-- 200 ") -> {
                        httpStringBuilder.append(HTTP__START_RESPONSE_TAG + "\n")
                        addHttpLogInfo(msg)
                    }
                    msg.startsWith("<-- END HTTP") -> {
                        addHttpLogInfo(msg)
                        httpStringBuilder.append(HTTP__END_RESPONSE_TAG + "\n")
                    }
                    else -> addHttpLogInfo(msg)
                }
            }

            private fun addHttpLogInfo(msg: String) {
                if (msg.startsWith("{")) {
                    val json = formatJson(msg)
                    httpStringBuilder.append(json)
                } else httpStringBuilder.append(msg)
                httpStringBuilder.append("\n")
            }

            @SuppressLint("LogNotTimber")
            private fun formatJson(msg: String): String {
                var formattedJsonString = ""

                try {
                    val jsonParser = JsonParser()
                    val jsonElement = jsonParser.parse(msg)
                    formattedJsonString = gson.toJson(jsonElement)
                } catch (e: Exception) {
                    Log.i(TAG, "formatJson: 错误$msg")
                }
                return formattedJsonString
            }
        }

    }

}

